package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.util.SMSUtils;
import com.itheima.reggie.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService service;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //1. 获取用户提交的手机号
        log.info("接收到发短信请求,手机号:{}",user.getPhone());

        try {
            //2. 调用阿里云服务发送短信验证码
            //2.1 通过工具类生成验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("本次生成验证码:{}",code);
            /*SMSUtils.sendMessage("阿里云短信测试","SMS_154950909",
                    user.getPhone(),code);*/


            //3. 将验证码存入session
            //session.setAttribute(user.getPhone(),code);

            //优化: 验证码使用redis管理,并设置5分钟内有效
            redisTemplate.opsForValue().set(user.getPhone(),code,5, TimeUnit.MINUTES);

            return R.success("验证码发送成功!");
        } catch (Exception e) {
            e.printStackTrace();
            return R.success("验证码发送失败!");
        }
    }

    @PostMapping("/login")
    public R<String> login(@RequestBody Map<String,String> map,HttpSession session){
        log.info("手机端登录功能,入参:{}",map);

        //1.拿到用户提交的手机号和密码
        String phone = map.get("phone");
        String code_input = map.get("code");

        //2.拿到服务器session中存储的验证码
        //String code_server = session.getAttribute(phone).toString();

        //优化: 拿到服务器redis中存储的验证码
        String code_server = (String) redisTemplate.opsForValue().get(phone);

        //3. 比对验证码
        if (code_input != null && code_input.equals(code_server)){

            //4. 判断当前手机号是否已经注册过
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(phone!= null,User::getPhone,phone);
            User user = service.getOne(wrapper);

            if (user == null){
                user = new User();
                user.setPhone(phone);
                //默认状态置为启动
                user.setStatus(1);
                service.save(user);
            }

            //将用户id存入session
            session.setAttribute("user",user.getId());

            //登录成功,则将验证码从缓存中移除
            redisTemplate.delete(phone);
            return R.success("登录成功!");
        }else {
            return R.error("登录失败!验证码错误!");
        }
    }
}
